const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { merge } = require("webpack-merge");
const dveConfig = require("./webpack.dev");
const prodConfig = require("./webpack.prod");

const getCommonConfig = function (isProd) {
  return {
    entry: "./src/main.js",
    devtool: false,
    output: {
      filename: "js/[name]_[chunkhash:5].js",
      path: path.resolve(__dirname, "./dist"),
      clean: true,
    },
    target: "web",
    resolve: {
      extensions: [".js", ".json", ".jsx", ".vue", ".ts"],
    },
    module: {
      rules: [
        {
          test: /\.m?jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
          },
        },
        {
          test: /\.css$/,
          // 开发时使用style-loader, 生产时使用MiniCssExtractPlugin.loader
          use: [
            isProd ? MiniCssExtractPlugin.loader : "style-loader",
            "css-loader",
          ],
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: "./index.html",
      }),
    ],
  };
};

module.exports = function (env) {
  const isProd = env.production;
  let mergeConfig = isProd ? prodConfig : dveConfig;
  return merge(getCommonConfig(isProd), mergeConfig);
};
